<?php

namespace App\Model;

//在活动期间关注公众号的用户
class MpInActivitySubscribeUserModel
{
    private static string $table = 'brz_mp_qr_def_subscribe_user';

    const flagSubscribe = 1;//关注
    const flagUnSubscribe = 0;//取消关注

    public function add(string $openid, int $flag, string $nickname)
    {
        if (!self::exist($openid, $flag)) {
            $client = (new MysqliFactory())->createMysqlClient();
            $data   = [
                'openid'   => $openid,
                'flag'     => $flag,
                'nickname' => $nickname,
                'add_time' => time(),
            ];
            $client->queryBuilder()->insert(self::$table, $data);
            try {
                $client->execBuilder();
            } catch (\Throwable $e) {
                echo $e->getMessage(), PHP_EOL;
            }
        }
    }

    private function exist(string $openid, int $flag): bool
    {
        $client = (new MysqliFactory())->createMysqlClient();
        $client->queryBuilder()
            ->where('openid', $openid)
            ->where('flag', $flag)
            ->get(self::$table);
        try {
            $ret = $client->execBuilder();
            if (!$ret) {
                return false;
            }
            return true;
        } catch (\Throwable $e) {
            echo $e->getMessage(), PHP_EOL;
            return false;
        }
    }

    /**
     * 是否允是新关注的用户
     * @param string $openid
     * @return bool
     */
    public function isNewSubscribe(string $openid): bool
    {
        //1.条件1 活动期间存在关注记录
        $existSub = self::exist($openid, self::flagSubscribe);
        //2.条件2 活动期间不存在取关记录
        $existUnsub = self::exist($openid, self::flagUnSubscribe);
        return $existSub && !$existUnsub;
    }

    public function getNickname(string $openid): string
    {
        try {
            $client = (new MysqliFactory())->createMysqlClient();
            $client->queryBuilder()
                ->where('openid', $openid)
                ->where('flag', self::flagSubscribe)
                ->get(self::$table);
            $ret = $client->execBuilder();
            if (isset($ret[0])) {
                return $ret[0]['nickname'];
            } else {
                return '';
            }
        } catch (\Throwable $e) {
            echo $e->getMessage(), PHP_EOL;
            return '';
        }
    }
}
